<template>
  <div class="flow-direction-container">
    <div class="table-top-container">
      <el-row>
        <el-col :span="12">
          <el-button
            class="border-btn"
            size="mini"
            @click="changeDistributeRelation"
          >变更终端配送信息</el-button>
          <span style="margin-left:10px">
            <i
              class="iconfont icon-tishi"
              style="font-size:14px;color:#666;line-height:18px"
            />
            <label style="font-size:14px;color:#666;line-height:18px">此功能为批量更换当前配送商下配送终端的配送信息</label></span>
        </el-col>
        <el-col :span="12">
          <div style="display: flex; justify-content: flex-end">
            <el-form
              :model="filterData"
              label-position="right"
              size="small"
              class="filter-form-inline"
            >
              <el-row
                :gutter="40"
                style="margin-left: 0px; margin-right: 0px"
              >
                <el-form-item
                  label="关键字"
                  style="width:300px;margin-right:20px;"
                >
                  <div style="display:flex;align-item:center;">
                    <el-input
                      v-model="filterData.keyWord"
                      clearable
                      placeholder="输入终端名称、渠道客户名称、关联配送服务编号"
                      @clear="refreshList"
                      @blur="refreshList"
                    />
                    <el-tooltip
                      class="box-item"
                      style="margin-left:4px;"
                      effect="dark"
                      content="输入终端名称、渠道客户名称、关联配送服务编号"
                      placement="top"
                    >
                      <i class="iconfont icon-wenhao" />
                    </el-tooltip>
                  </div>
                </el-form-item>
                <el-form-item>
                  <filter-popover
                    right="20px"
                    :form-list="formList"
                    @onConfirm="filterDataConfirm"
                    @onReset="filterReset"
                  />
                </el-form-item>
                <el-form-item style="margin-left: 20px;">
                  <table-cell-setting
                    :table-option="tableOption"
                    :checked="checkListData"
                    @checkList="checkList"
                  />
                </el-form-item>
              </el-row>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="table-list">
      <el-table
        :data="listData"
        header-cell-class-name="table-header"
        border
        :cell-style="cellStyle"
        style="width: 100%"
        @row-click="rowClick"
      >
        <el-table-column
          v-if="checkListData.indexOf('terminalName') !==-1"
          prop="terminalName"
          label="终端名称"
          fixed="left"
          :min-width="160"
          show-overflow-tooltip
          header-align="center"
        >
          <template #default="scope">
            <div>
              <el-link
                type="primary"
                :underline="false"
              >{{ scope.row.terminalName }}</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('area') !==-1"
          prop="area"
          label="所在地区"
          :min-width="180"
          show-overflow-tooltip
          header-align="center"
        >
          <template #default="scope">
            <div>{{ scope.row.provinceName }} / {{ scope.row.cityName }} / {{ scope.row.areaName }}</div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('terminalPrice') !==-1"
          label="终端价（元）"
          prop="terminalPrice"
          header-align="center"
          align="center"
          :width="120"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="checkListData.indexOf('agentName') !==-1"
          prop="agentName"
          label="渠道客户名称"
          header-align="center"
          :min-width="140"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="checkListData.indexOf('productPopularName') !==-1"
          prop="productPopularName"
          label="产品名称"
          header-align="center"
          :min-width="140"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div>
              <el-link
                type="primary"
                :underline="false"
              >{{ scope.row.productPopularName }}</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('approvalNumber') !==-1"
          prop="approvalNumber"
          label="批准文号"
          header-align="center"
          :min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="checkListData.indexOf('packSpecs') !==-1"
          prop="packSpecs"
          label="包装规格"
          header-align="center"
          :min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div>
              <span>{{ scope.row.packSpecs }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('distributePrice') !==-1"
          prop="distributePrice"
          label="配送费"
          header-align="center"
          :min-width="150"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div style="line-height:20px;">
              <div class="distribute-price">
                <div v-if="scope.row.computeMode==='固定价格'">
                  <span>{{ scope.row.distributePrice }}元</span><span v-if="scope.row.sellUnit"> / {{ getLabel('sell_unit',scope.row.sellUnit) }}</span>
                </div>
                <div v-if="scope.row.computeMode==='终端价百分比'">
                  <span>{{ scope.row.distributePrice }}%</span><span>终端价</span>
                </div>
              </div>
              <div class="distribute-price-status">
                <span
                  v-if="scope.row.distributeDetailStatus==='DOING'"
                  class="flow-status-color"
                >[ 配送费变更审核中 ]</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('distributeServeNo') !==-1"
          prop="distributeServeNo"
          label="关联配送服务"
          header-align="center"
          :width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div>
              <el-link
                type="primary"
                :underline="false"
              >{{ scope.row.distributeServeNo }}</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('devStandardStatus') !==-1"
          label="进货关系状态"
          header-align="center"
          align="center"
          :min-width="120"
          show-overflow-tooltip
          fixed="right"
        >
          <template #default="scope">
            <span>{{ getLabel('dev_status_terminal',scope.row.devStandardStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('rddStatus') !==-1"
          label="配送状态"
          header-align="center"
          align="center"
          :width="160"
          show-overflow-tooltip
          fixed="right"
        >
          <template #default="scope">
            <div style="line-height:20px;">
              <div>{{ getLabel('distribute_status',scope.row.rddStatus) }}</div>
              <div
                v-if="scope.row.rddStatus==='1'"
                class="distribute-price-status"
              >
                <span
                  v-if="scope.row.flowStatus==='DOING'"
                  class="flow-status-color"
                >[ 配送信息变更审核中 ]</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          header-align="center"
          :width="120"
          show-overflow-tooltip
          fixed="right"
        >
          <template #default="scope">
            <el-button
              v-if="scope.row.rddStatus === '-1'"
              class="danger"
              type="text"
              @click="deleteRow(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-model:page="filterData.page"
        v-model:limit="filterData.pageSize"
        style="display: flex; justify-content: flex-end"
        :total="total"
        @pagination="refreshList"
      />
    </div>
    <change-distribute-relation
      ref="distributeRelationRef"
      @onSuccess="refreshList"
    />
    <!-- 产品详情 -->
    <detail-drawer
      ref="proDetailDrawer"
      custom-title
    >
      <template #title>
        <span>产品详情 {{ rowData?.productPopularName }}-{{ rowData?.approvalNumber }}-{{ rowData?.packSpecs }}</span>
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <item-title title="基本信息" />
            <product-base-info
              v-if="productId"
              :id="productId"
            />
          </div>
          <div class="history-list">
            <item-title title="修改记录" />
            <operation-view
              v-if="productId"
              :id="productId"
              mode="product"
            />
          </div>
        </div>
      </template>
    </detail-drawer>
    <!-- 配送服务详情 -->
    <detail-drawer
      ref="serviceDetailDrawer"
      custom-title
    >
      <template #title>
        <span>配送服务详情</span>
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <item-title title="基本信息" />
            <distributor-service-info
              v-if="distributeServeId"
              :id="distributeServeId"
            />
          </div>
          <div class="history-list">
            <item-title title="修改记录" />
            <operation-view
              v-if="distributeServeId"
              :id="distributeServeId"
              mode="distribute_serve"
            />
          </div>
        </div>
      </template>
    </detail-drawer>
    <!--配送终端关系详情-->
    <detail-drawer
      ref="relationDrawer"
      custom-title
      :size-width="1000"
    >
      <template #title>
        <span>配送终端关系 - {{ rowData?.terminalName }}</span>
        <!--rowData?.tagType-->
        <el-tag
          v-if="rowData?.rddStatus"
          size="small"
          style="margin-left: 5px"
          type="warning"
        >
          <span>{{ getLabel('distribute_status',rowData?.rddStatus) }}</span>
          <span
            v-if="rowData?.rddStatus==='1'&&rowData?.flowStatus==='DOING'"
            style="margin-left:4px;"
          >[ 配送信息变更审核中 ]</span>
        </el-tag>
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <relationship
              ref="relationshipRef"
              :trading-product-id="rowData?.devDistributeId"
              :api-data="{apiFile: 'common',apiPath: 'DEV_TERMINAL_DETAIL'}"
            />
          </div>
          <div
            class="history-list"
            style="margin-top:20px;"
          >
            <item-title title="修改记录" />
            <operation-view
              :id="rowData?.id"
              mode="dev"
            />
          </div>
        </div>
      </template>
    </detail-drawer>
    <!--终端详情-->
    <detail-drawer
      ref="terminalDrawer"
      custom-title
    >
      <template #title>
        <span>终端信息 - {{ rowData?.terminalName }}</span>
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <terminal-info :id="rowData?.terminalId" />
          </div>
        </div>
      </template>
    </detail-drawer>
  </div>
</template>

<script>
import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, onMounted, reactive, ref, toRefs,} from 'vue'
import {useRoute} from 'vue-router'
import {crmStore} from '@CRM/store'

export default defineComponent({
  components: {
    changeDistributeRelation: defineAsyncComponent(() =>
      import('./modules/changeDistributeRelation.vue')
    ),
    productBaseInfo: defineAsyncComponent(() =>
      import(
        '@CRM/views/commonView/detailComponents/product/productBaseInfo.vue'
      )
    ),
    distributorServiceInfo: defineAsyncComponent(() =>
      import(
        '@CRM/views/commonView/detailComponents/distributor/distributorServiceInfo.vue'
      )
    ),
    relationship: defineAsyncComponent(() =>
      import(
        '@CRM/views/commonView/detailComponents/relationship/relationship.vue'
      )
    ),
    terminalInfo: defineAsyncComponent(() =>
      import('@CRM/views/commonView/detailComponents/terminal/terminalInfo.vue')
    ),
  },
  props: {
    detail: {
      type: Object,
      default: () => {},
    },
  },
  setup(props, context) {
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const route = useRoute()
    var distributeRelationRef = ref(null)
    var proDetailDrawer = ref(null)
    var serviceDetailDrawer = ref(null)
    var relationDrawer = ref(null)
    var relationshipRef = ref(null)
    var terminalDrawer = ref(null)
    var reactiveData = reactive({
      distributorId: Number(route.query.id),
      productId: 0,
      distributeServeId: 0,
      rowData: null,
      checkListData: [
        'terminalName',
        'area',
        'terminalPrice',
        'agentName',
        'productPopularName',
        'approvalNumber',
        'packSpecs',
        'distributePrice',
        'distributeServeNo',
        'devStandardStatus',
        'rddStatus',
      ],
      tableOption: [
        {
          key: 'terminalName',
          value: '终端名称',
        },
        {
          key: 'area',
          value: '所在地区',
        },
        {
          key: 'terminalPrice',
          value: '终端价',
        },
        {
          key: 'agentName',
          value: '渠道客户名称',
        },
        {
          key: 'productPopularName',
          value: '产品名称',
        },
        {
          key: 'approvalNumber',
          value: '批准文号',
        },
        {
          key: 'packSpecs',
          value: '包装规格',
        },
        {
          key: 'distributePrice',
          value: '配送费',
        },
        {
          key: 'distributeServeNo',
          value: '关联配送服务',
        },
        {
          key: 'devStandardStatus',
          value: '进货关系状态',
        },
        {
          key: 'rddStatus',
          value: '配送状态',
        },
      ],
      listData: [],
      total: 0,
      filterData: {
        page: 1,
        pageSize: 20,
        distributeId: Number(route.query.id),
        productId: 0,
        devStandardStatus: '',
        rddStatus: '',
        keyWord: '',
        provinceCode: '',
        cityCode: '',
        areaCode: '',
      },
      formList: [
        // {
        //   key: 'devStandardStatus',
        //   label: '进货关系状态',
        //   form_type: 'select',
        //   value: '',
        //   is_search: false,
        //   options:
        //     crmStore.getters['dictionary/getDictionary']['dev_status_terminal'],
        // },
        {
          key: 'rddStatus',
          label: '配送状态',
          form_type: 'select',
          value: '',
          is_search: false,
          options:
            crmStore.getters['dictionary/getDictionary']['distribute_status'],
        },
        {
          key: 'productId',
          label: '产品',
          form_type: 'select',
          value: undefined,
          is_search: true,
          loading: false,
          setting: {
            api_file: 'common',
            api_name: 'GET_PRODUCT_LIST',
            key_word: 'keyWord',
            label: 'productPopularName',
            value: 'id',
          },
          options: [],
        },
        {
          key: 'area',
          label: '所在地区',
          form_type: 'cascader',
          value: [],
          is_search: false,
          options: [],
        },
      ],
    })
    const checkList = (checked) => {
      reactiveData.checkListData = checked
    }
    const cellStyle = (row) => {
      if (row.column.label === '操作') return
      return 'cursor: pointer;'
    }
    const rowClick = (row, column, event) => {
      console.log(row, column.label, event)
      if (column.label === '操作') return
      if (column.label === '终端名称') {
        reactiveData.rowData = row
        terminalDrawer.value.open()
      } else if (column.label === '产品名称') {
        toProductDetail(row)
      } else if (column.label === '关联配送服务') {
        toServiceDetail(row)
      } else {
        toRelationDetail(row)
      }
    }
    const changeDistributeRelation = () => {
      distributeRelationRef.value.open(props.detail)
    }
    const getDistributeTerminalList = () => {
      api.distributors
        .DISTRIBUTORS_TERMINAL_RELATION_LIST(reactiveData.filterData)
        .then((res) => {
          if (res.code === 0) {
            reactiveData.listData = res.data.list
            reactiveData.total = res.data.total
          }
        })
    }
    const refreshList = () => {
      getDistributeTerminalList()
    }
    const toProductDetail = (row) => {
      reactiveData.rowData = row
      reactiveData.productId = row.productId
      proDetailDrawer.value.open()
    }
    const toServiceDetail = (row) => {
      reactiveData.rowData = row
      reactiveData.distributeServeId = row.distributeDetailId
      serviceDetailDrawer.value.open()
    }
    const toRelationDetail = (row) => {
      var tagType = ''
      if (row.rddStatus === '1') {
        tagType = 'success'
      } else if (row.rddStatus === '0') {
        tagType = 'warning'
      } else {
        tagType = 'error'
      }
      reactiveData.rowData = { ...row, tagType: tagType }
      relationDrawer.value.open()
    }
    const filterReset = () => {
      reactiveData.filterData = {
        page: 1,
        pageSize: 20,
        distributeId: Number(route.query.id),
        productId: 0,
        devStandardStatus: '',
        rddStatus: '',
        keyWord: '',
        provinceCode: '',
        cityCode: '',
        areaCode: '',
      }
      getDistributeTerminalList()
    }
    const filterDataConfirm = (formdata) => {
      reactiveData.filterData.devStandardStatus = formdata.devStandardStatus
      reactiveData.filterData.rddStatus = formdata.rddStatus
      reactiveData.filterData.productId = formdata.productId || null
      // 所在地区
      if (formdata.area && formdata.area.length) {
        reactiveData.filterData.provinceCode = formdata.area[0]
        reactiveData.filterData.cityCode = formdata.area[1]
        reactiveData.filterData.areaCode = formdata.area[2]
      } else {
        reactiveData.filterData.provinceCode = ''
        reactiveData.filterData.cityCode = ''
        reactiveData.filterData.areaCode = ''
      }

      getDistributeTerminalList()
    }

    const deleteRow = (row) => {
      currentInstance.proxy
        .alertBox({
          title: '删除',
          message: '数据删除后不可恢复，确定删除？',
        })
        .then(() => {
          api.distributors
            .DISTRIBUTORS_RELATION_DELETE({ id: row.devDistributeId })
            .then((res) => {
              if (res.code === 0) {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '删除成功',
                })
                getDistributeTerminalList()
              } else {
                currentInstance.proxy.customMessage({
                  type: 'error',
                  message: res.msg,
                })
              }
            })
        })
    }

    onMounted(() => {
      getDistributeTerminalList()
    })

    return {
      cellStyle,
      rowClick,
      distributeRelationRef,
      proDetailDrawer,
      serviceDetailDrawer,
      relationDrawer,
      relationshipRef,
      terminalDrawer,
      ...toRefs(reactiveData),
      checkList,
      changeDistributeRelation,
      refreshList,
      toProductDetail,
      toServiceDetail,
      toRelationDetail,
      filterReset,
      filterDataConfirm,
      deleteRow,
    }
  },
})
</script>

